# serializers.py in the users Django app
from django.db import transaction
from rest_framework import serializers
from dj_rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers
from accounts.models import GENDER_SELECTION, CustomUser
from genomes.models import Genome


class CustomUserSerializer(serializers.HyperlinkedModelSerializer):

    genome_set = serializers.HyperlinkedRelatedField(
        many=True, view_name="genome-detail", read_only=True)
    # genome_set = serializers.PrimaryKeyRelatedField(
    #     many=True, queryset=Genome.objects.all())

    class Meta:
        model = CustomUser
        extra_kwargs = {
            'url': {'view_name': 'user-detail', 'lookup_field': 'pk'}
        }
        fields = ['url', 'id', 'username', 'email',
                  'gender', 'phone_number', 'genome_set']


class CustomRegisterSerializer(RegisterSerializer):
    gender = serializers.ChoiceField(choices=GENDER_SELECTION)
    phone_number = serializers.CharField(max_length=30)

    # Define transaction.atomic to rollback the save operation in case of error
    @transaction.atomic
    def save(self, request):
        user = super().save(request)
        user.gender = self.data.get('gender')
        user.phone_number = self.data.get('phone_number')
        user.save()
        return user
